global !p

from mdtex.scopes import math, not_unit
from mdtex.cmdsub import command_swap

endglobal

################################################################
#                                                              #
#               Operators - Fraction & Binomial                #
#                                                              #
################################################################

context "math() and not_unit()"
snippet // "分数 Fraction" iA
\dfrac{${1:${VISUAL}}}{$2}$0
endsnippet

context "math()"
snippet "\(.*\)/" "大型括号分数 Large Parenthes Fraction" rA
`!p
string = match.group(0)[:-1]
depth = 0
for i in range(len(string) - 1, -1, -1):
    char = string[i]
    if char == ')':
        depth += 1
    elif char == '(':
        depth -= 1
    if not depth:
        break
snip.rv = string[:i] + "\\dfrac{" + string[i + 1:-1] + "}"
`{$1}$0
endsnippet

context "math()"
snippet bin "二项式 Binomial" w
\dbinom{${1:${VISUAL}}}{$2}$0
endsnippet

priority -1

# 支持数字、（数字或字母加）字母或字符命令（加上下标）与阶乘等
# Support number, (number or letter add) letter or string command (add superscript or subscript) and factorial
# 字符命令指的是 '\alpha' 等
# String command refers to as '\alpha' and so on
context "math() and not_unit()"
snippet "([a-zA-Z\d]+!?|[a-zA-Z\d]*\\?[A-Za-z]+([_^](\{[^}]+\}|[\da-zA-Z])){,2})/" "简单分数 Simple Fraction" Ar
\dfrac{`!p snip.rv = match.group(1)`}{${1:${VISUAL}}}$0
endsnippet

# frac <-> dfrac
context "math()"
snippet "(\\(d?frac)\{.*\}\{.*\})" "分式变形 Fraction Transformation" r
`!p snip.rv = command_swap(match.group(1), '\\frac', '\\dfrac', 2)`
endsnippet

context "math()"
snippet "(\\(d?binom)\{.*\}\{.*\})" "二项式变形 Binomial Transformation" r
`!p snip.rv = command_swap(match.group(1), '\\binom', '\\dbinom', 2)`
endsnippet
